from common.models.statistics import StatDailyFood
from common.models.statistics import StatDailyMember
from common.models.statistics import StatDailySite
from common.models.food import FoodSaleChangeLog
from common.models.food import WxShareHistory
from common.libs.Helper import getFormatDate
from common.libs.Helper import getCurrentDate
from common.models.member import Member
from common.models.pay import PayOrder
from common.models.food import Food
from application import app,db

from sqlalchemy import func
import datetime
import random

class JobTask(object):
    """
    该Job用于处理异步统计处理
    """

    def __init__(self):
        pass

    def run(self, params):
        act = params['act'] if params['act'] else ''
        date = params['param'][0] if params['param'] else getFormatDate(format='%Y-%m-%d')

        if not act:
            return False

        # 定义查询的时间
        date_from = date + ' 00:00:00'
        date_to = date + ' 23:59:59'

        func_param = {
            'act':act,'date': date, 'date_from': date_from, 'date_to': date_to
        }

        if act == 'member':
            self.memberStatistics(func_param)
        if act == 'food':
            self.foodStatistics(func_param)
        if act == 'site':
            self.siteStatistics(func_param)

        # 测试调用模拟数据生成
        if act == 'test':
            self.test()

    def memberStatistics(self, func_param):
        """
        会员统计
        :param func_param:
        :return:
        """
        date = func_param['date']
        date_to = func_param['date_to']
        date_from = func_param['date_from']

        app.logger.info(func_param)

        member_list = Member.query.all()

        if not member_list:
            app.logger.info('member is empty!')
            return False

        for member in member_list:
            stat_member_info =StatDailyMember.query.filter_by(date=date,member_id = member.id).first()
            if stat_member_info:
                model_stat_member = stat_member_info
            else:
                model_stat_member = StatDailyMember()
                model_stat_member.date = date
                model_stat_member.member_id = member.id
                model_stat_member.created_time = getCurrentDate()

            # 统计会员当天分享的次数
            temp_share_count = WxShareHistory.query.filter(WxShareHistory.member_id==member.id)\
                .filter(WxShareHistory.created_time>=date_from,WxShareHistory.created_time<=date_to).count()

            # 统计会员当天的支付的金额
            temp_pay_money = db.session.query(func.sum(PayOrder.total_price).label('total')).filter(PayOrder.status==1)\
                .filter(PayOrder.member_id==member.id).filter(PayOrder.created_time>=date_from,PayOrder.created_time<=date_to).first()

            model_stat_member.total_shared_count = temp_share_count
            model_stat_member.total_pay_money =temp_pay_money[0] if temp_pay_money[0] else 0.00

            """
            为了测试效果，模拟数据
            """
            model_stat_member.total_shared_count =random.randint(10,100)
            model_stat_member.total_pay_money =random.randint(500,2000)

            model_stat_member.updated_time = getCurrentDate()
            model_stat_member.save()

    def foodStatistics(self, func_param):
        """
        美食销售统计
        :param func_param:
        :return:
        """
        date = func_param['date']
        date_to = func_param['date_to']
        date_from = func_param['date_from']

        app.logger.info(func_param)

        # 采用分组查询
        food_sale_list = db.session.query(FoodSaleChangeLog.food_id,func.sum(FoodSaleChangeLog.quantity).label('total_count'),
                                          func.sum(FoodSaleChangeLog.price).label('total_pay_money'))\
            .filter(FoodSaleChangeLog.created_time>=date_from,FoodSaleChangeLog.created_time<=date_to)\
            .group_by(FoodSaleChangeLog.food_id).all()

        if not food_sale_list:
            app.logger.info('no data!')
            return False

        for item in food_sale_list:
            food_id = item[0]
            stat_food_info = StatDailyFood.query.filter_by(date=date, food_id=food_id).first()
            if stat_food_info:
                model_stat_food = stat_food_info
            else:
                model_stat_food = StatDailyFood()
                model_stat_food.date = date
                model_stat_food.food_id = food_id
                model_stat_food.created_time = getCurrentDate()

            model_stat_food.total_count = item[1] if item[1] else 0
            model_stat_food.total_pay_money = item[2] if item[2] else 0.00

            """
            为了测试效果，模拟数据
            """
            model_stat_food.total_count = random.randint(10, 100)
            model_stat_food.total_pay_money = random.randint(500, 2000)

            model_stat_food.updated_time = getCurrentDate()
            model_stat_food.save()

    def siteStatistics(self, func_param):
        """
        全站统计
        :param func_param:
        :return:
        """
        date = func_param['date']
        date_to = func_param['date_to']
        date_from = func_param['date_from']

        app.logger.info(func_param)

        # 当日总的支付金额
        total_money = db.session.query(func.sum(PayOrder.total_price).label('total_money')).filter(PayOrder.status==1)\
            .filter(PayOrder.created_time>=date_from,PayOrder.created_time<=date_to).first()

        # 会员总数
        total_member = Member.query.filter(Member.status==1).count()

        # 当日新增会员数
        new_member_count = Member.query.filter(Member.status==1)\
            .filter(Member.created_time>=date_from,Member.created_time<=date_to).count()

        # 当日订单数
        total_order = PayOrder.query.filter(PayOrder.created_time>=date_from,PayOrder.created_time<=date_to)\
            .filter(PayOrder.status==1).count()

        # 当日分享次数
        total_share = WxShareHistory.query.filter(WxShareHistory.created_time>=date_from,WxShareHistory.created_time<=date_to).count()

        temp_site_info = StatDailySite.query.filter(StatDailySite.date==date).first()
        if temp_site_info:
            model_site = temp_site_info
        else:
            model_site = StatDailySite()
            model_site.date = date
            model_site.created_time = getCurrentDate()

        model_site.total_pay_money = total_money[0] if total_money[0] else 0.00
        model_site.total_member_count = total_member
        model_site.total_new_member_count = new_member_count
        model_site.total_order_count = total_order
        model_site.total_shared_count = total_share

        """
        测试模拟数据
        """
        model_site.total_pay_money = random.randint(1000,5000)
        model_site.total_new_member_count = random.randint(10,100)
        model_site.total_member_count = model_site.total_new_member_count + random.randint(1000,2000)
        model_site.total_order_count = random.randint(100,500)
        model_site.total_shared_count = random.randint(50,300)

        model_site.updated_time = getCurrentDate()
        model_site.save()

    def test(self):
        """
        该函数用于模拟一个月的数据
        :return:
        """
        for i in reversed(range(31)):
            now_date = datetime.datetime.now()
            before_date = now_date - datetime.timedelta(days=i)
            date = getFormatDate(before_date,format='%Y-%m-%d')
            params = {
                'act': 'test',
                'date':date,
                'date_from':date + ' 00:00:00',
                'date_to': date  + ' 23:59:59',
            }
            self.testFoodSale(date)
            self.memberStatistics(params)
            self.foodStatistics(params)
            self.siteStatistics(params)

    def testFoodSale(self,date):
        """
        该函数模拟美食销售数据
        :param date:
        :return:
        """
        food_list = Food.query.filter(Food.status==1).all()

        if not food_list:
            app.logger.info('no food!')
            return False

        for food in food_list:
            model_food_sale = FoodSaleChangeLog()
            model_food_sale.food_id = food.id
            model_food_sale.quantity = random.randint(10,50)
            model_food_sale.price = model_food_sale.quantity *food.price
            model_food_sale.member_id = 1
            model_food_sale.created_time = date +" "+ getFormatDate(format='%H:%M:%S')
            model_food_sale.save()



